from transformers import Qwen2VLForConditionalGeneration, AutoProcessor
from qwen_vl_utils import process_vision_info
import torch

# 指定本地模型路径
model_dir = 'D:/work/program/pytorch_models/Qwen/Qwen2-VL-2B-Instruct-GPTQ-Int8'

# 加载模型
model = Qwen2VLForConditionalGeneration.from_pretrained(
    model_dir,
    torch_dtype=torch.float32,  # 使用 float32 数据类型
    device_map="cpu"  # 使用 CPU
)

# 加载处理器
processor = AutoProcessor.from_pretrained(model_dir)

# 输入消息
messages = [
    {
        "role": "user",
        "content": [
            {
                "type": "image",
                "image": "file://D:\\work\\tmp\\05_xugf\\1751424332680JC745a5411dea8c9040a092aec5b9b6511548.jpg",
            },
            {"type": "text", "text": "描述一下这张图片"},
        ],
    }
]

# 准备推理
text = processor.apply_chat_template(
    messages, tokenize=False, add_generation_prompt=True
)
image_inputs, video_inputs = process_vision_info(messages)
inputs = processor(
    text=[text],
    images=image_inputs,
    videos=video_inputs,
    padding=True,
    return_tensors="pt",
)

# 将输入数据移动到 CPU
inputs = inputs.to("cpu")

# 推理：生成输出
generated_ids = model.generate(**inputs, max_new_tokens=128)
generated_ids_trimmed = [
    out_ids[len(in_ids):] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
]
output_text = processor.batch_decode(
    generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
)
print(output_text)